#include "headers/markedprocessmanagerdialog.h"
#include "ui_markedprocessmanagerdialog.h"
#include "headers/MarkedGameManager.h"
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonArray>

MarkedProcessManagerDialog::MarkedProcessManagerDialog(MarkedGameManager *manager, QWidget *parent)
    : QDialog(parent),
    ui(new Ui::MarkedProcessManagerDialog),
    m_markedManager(manager)
{
    ui->setupUi(this);
    setWindowTitle("标记进程管理");
    setFixedSize(400, 300);

    connect(ui->deleteBtn, &QPushButton::clicked, this, &MarkedProcessManagerDialog::onDeleteBtnClicked);
    connect(ui->refreshBtn, &QPushButton::clicked, this, &MarkedProcessManagerDialog::onRefreshBtnClicked);
    connect(ui->closeBtn, &QPushButton::clicked, this, &QDialog::close);

    loadMarkedProcesses();
}

MarkedProcessManagerDialog::~MarkedProcessManagerDialog()
{
    delete ui;
}

// 加载已标记的进程列表
void MarkedProcessManagerDialog::loadMarkedProcesses()
{
    ui->processListWidget->clear();
    QStringList markedProcesses = m_markedManager->loadMarkedGames();

    if (markedProcesses.isEmpty()) {
        ui->emptyTipLabel->show();
        ui->processListWidget->hide();
        ui->deleteBtn->setEnabled(false);
    } else {
        ui->emptyTipLabel->hide();
        ui->processListWidget->show();
        ui->deleteBtn->setEnabled(true);
        for (const QString &process : markedProcesses) {
            new QListWidgetItem(process, ui->processListWidget);
        }
    }
}

// 删除选中的进程
void MarkedProcessManagerDialog::onDeleteBtnClicked()
{
    QListWidgetItem *selected = ui->processListWidget->currentItem();
    if (!selected) {
        QMessageBox::warning(this, "提示", "请先选中要删除的进程！");
        return;
    }

    QString processName = selected->text();
    if (QMessageBox::question(this, "确认删除",
                              QString("是否删除标记进程「%1」？").arg(processName),
                              QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
        if (m_markedManager->removeMarkedGame(processName)) {
            QMessageBox::information(this, "成功", "进程删除成功！");
            loadMarkedProcesses();
            emit markedProcessUpdated();
        } else {
            QMessageBox::critical(this, "失败", "进程删除失败！");
        }
    }
}

// 刷新进程列表
void MarkedProcessManagerDialog::onRefreshBtnClicked()
{
    loadMarkedProcesses();
}
